import { useState, useEffect } from "react";
import { Alert, Button, Form, Input, message, Popconfirm, Popover, Space, Switch, Table, Tooltip } from "antd";
import { goodsSkuGetSkuList, goodsSkuModifySku, goodsSkuTypeDeleteSkuType } from "@/api/modules/goodsSku";
import type { GoodsSkuGetSkuListItemModel } from "@/api/modules/goodsSku";
import useSyncState from "@/hooks/useSyncState";
import {
	CheckCircleOutlined,
	CloseCircleOutlined,
	DeleteOutlined,
	FormOutlined,
	PlusOutlined,
	SearchOutlined
} from "@ant-design/icons";
import dayjs from "dayjs";
import _ from "lodash";

interface ListQuery {
	page: number;
	size: number;
	total: number;
}
const skuCategory = () => {
	/** 初始化数据 */
	const [tableData, setTableData] = useState<GoodsSkuGetSkuListItemModel[]>([]);
	const [tableDataBackup, setTableDataBackup] = useState<GoodsSkuGetSkuListItemModel[]>([]);

	const [listQuery, setListQuery, getListQuery] = useSyncState<ListQuery>({
		page: 1,
		size: 10,
		total: 0
	});
	const [loading, setLoading] = useState<boolean>(false);

	// 获取数据
	async function getList() {
		try {
			setLoading(true);
			const { code, data } = await goodsSkuGetSkuList(getListQuery());
			if (code === 0) {
				const newTableData = data.list.map(item => {
					item.edit = false;
					return item;
				});
				setTableData(_.cloneDeep(newTableData));
				setTableDataBackup(_.cloneDeep(newTableData));
				setListQuery({
					...getListQuery(),
					total: data.total
				});
			}
		} finally {
			setLoading(false);
		}
	}
	// 分页器变化回调
	function handleTableChange(pagination: any) {
		const listQueryRef: ListQuery = {
			page: pagination.current,
			size: pagination.pageSize,
			total: pagination.total
		};
		setListQuery(listQueryRef);
		getList();
	}
	/** sku修改或增加 */
	async function submitSku(item: GoodsSkuGetSkuListItemModel) {
		const { code, msg } = await goodsSkuModifySku({
			id: item.id ? item.id : undefined,
			k: item.k,
			largeImageMode: item.largeImageMode
		});
		if (code === 0) {
			message?.success(msg);
			getList();
			closePopover();
		}
	}
	function closePopover() {
		// 关闭弹出框
		setPopover({
			visible: false,
			k: "",
			largeImageMode: false,
			id: undefined
		});
	}
	/** 添加sku分类 */
	interface Popover {
		visible: boolean;
		k: string;
		largeImageMode: boolean;
		id?: number;
	}

	const [popover, setPopover] = useState<Popover>({
		visible: false,
		k: "",
		largeImageMode: false,
		id: undefined
	});
	// 修改表单失败回调
	const onFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 提交新增/修改表单
	const onFinish = async (form: any) => {
		console.log(form, "form");
		submitSku({ k: form.k, largeImageMode: form.largeImageMode });
	};
	useEffect(() => {
		getList();
	}, []);
	const columns: any[] = [
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "20%%",
			render: (createTime: number) => (
				<Tooltip placement="topLeft" title={dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}>
					{dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}
				</Tooltip>
			)
		},
		{
			title: "分类名称",
			dataIndex: "k",
			key: "k",
			align: "center",
			width: "20%",
			render: (_: any, record: GoodsSkuGetSkuListItemModel, index: number) => (
				<>
					{!record.edit && <>{record.k}</>}
					{record.edit && (
						<Input
							value={record.k}
							placeholder="输入分类名称"
							maxLength={200}
							showCount
							onChange={e => {
								tableData[index].k = e.target.value;
								setTableData([...tableData]);
							}}
						/>
					)}
				</>
			)
		},
		{
			title: "大图模式",
			dataIndex: "largeImageMode",
			key: "largeImageMode",
			align: "center",
			width: "20%",
			render: (_: any, record: GoodsSkuGetSkuListItemModel, index: number) => (
				<>
					{
						<Switch
							disabled={!record.edit}
							checked={record.largeImageMode}
							checkedChildren="启用"
							unCheckedChildren="禁用"
							onChange={(checked: boolean) => {
								tableData[index].largeImageMode = checked;
								setTableData([...tableData]);
							}}
						/>
					}
				</>
			)
		},
		{
			title: "操作",
			align: "center",
			key: "action",
			width: "40%",
			render: (_: any, record: GoodsSkuGetSkuListItemModel, index: number) => (
				<Space wrap>
					{!record.edit && (
						<Button
							type="primary"
							icon={<FormOutlined />}
							onClick={() => {
								tableData[index].edit = true;
								setTableData([...tableData]);
							}}
						>
							编辑
						</Button>
					)}
					{record.edit && (
						<>
							<Button
								onClick={() => {
									tableDataBackup[index].edit = false;
									setTableData(tableDataBackup);
								}}
								icon={<CloseCircleOutlined />}
							>
								取消
							</Button>
							<Button type="primary" icon={<CheckCircleOutlined />} onClick={() => submitSku(record)}>
								确定
							</Button>
						</>
					)}
					<Popconfirm title="确定执行该操作吗？" onConfirm={() => {}} okText="Yes" cancelText="No">
						<Button type="primary" danger icon={<DeleteOutlined />}>
							删除
						</Button>
					</Popconfirm>
				</Space>
			)
		}
	];
	// 添加分类表单
	const [form] = Form.useForm();
	const PopoverRenderDom = () => {
		return (
			<Form
				form={form}
				initialValues={{ largeImageMode: false }}
				preserve={false}
				size="middle"
				autoComplete="off"
				onFinish={onFinish}
				onFinishFailed={onFinishFailed}
			>
				<Alert
					message="提示：开启大图模式，商品选择该分类需要上传规格预览图"
					type="warning"
					showIcon
					closable
					className="!mb-10"
				/>
				<Form.Item label="分类名称" name="k" rules={[{ required: true, message: "请输入分类名称" }]}>
					<Input placeholder="输入分类名称" maxLength={200} showCount />
				</Form.Item>
				<Form.Item valuePropName="checked" label="大图模式" name="largeImageMode">
					<Switch checkedChildren="启用" unCheckedChildren="禁用" />
				</Form.Item>
				<Space className="mt-10">
					<Button onClick={() => closePopover()}>取消</Button>
					<Button type="primary" onClick={() => form.submit()}>
						确定
					</Button>
				</Space>
			</Form>
		);
	};
	return (
		<div className="skuCategory">
			<div className="skuCategory__title flex items-center justify-between mb-10">
				<Space className="flex items-center" size="large">
					<span className="text-18 font-bold">分类列表</span>
				</Space>
				<Space className="flex items-center">
					<Popover
						content={PopoverRenderDom()}
						placement="bottomRight"
						trigger="click"
						open={popover.visible}
						onOpenChange={(newOpen: boolean) => {
							setPopover({
								...popover,
								visible: newOpen
							});
						}}
					>
						<Button
							icon={<PlusOutlined />}
							onClick={() => {
								setPopover({
									...popover,
									visible: true
								});
							}}
						>
							添加Sku分类
						</Button>
					</Popover>
					<Button
						type="primary"
						icon={<SearchOutlined />}
						onClick={() => {
							getList();
						}}
					>
						查询
					</Button>
				</Space>
			</div>
			<div className="skuCategory__content">
				<Table
					loading={loading}
					bordered={false}
					dataSource={tableData}
					columns={columns}
					rowKey={record => record.id?.toString() ?? ""}
					scroll={{ x: true }}
					pagination={{
						current: listQuery.page, // 当前页码
						pageSize: listQuery.size, // 每页条数
						total: listQuery.total, // 数据总数
						showSizeChanger: true, // 显示每页条数切换器
						showQuickJumper: true // 显示快速跳转输入框
					}}
					onChange={pagination => handleTableChange(pagination)} // 分页变化回调
				/>
			</div>
		</div>
	);
};
export default skuCategory;
